package threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述：     演示ThreadLocal用法2：避免传递参数的麻烦
 */
public class ThreadLocalNormalUsage06 {

    public static void main(String[] args) {
//        new Service1().process("超哥");
//        new Service1().process("凤姐");

//        ExecutorService threadPool = Executors.newFixedThreadPool(2);
//        threadPool.execute(
//                ()->{new Service1().process("超哥");}
//        );
//
//        threadPool.execute(
//                ()->{new Service1().process("凤姐");}
//        );
//        threadPool.shutdown();

        new Thread(  ()->{new Service1().process("超哥");},"线程1").start();
        new Thread(  ()->{new Service1().process("凤姐");},"线程2").start();

    }
}

class Service1 {

    public void process(String name) {
        User user = new User(name);
        UserContextHolder.holder.set(user);
        new Service2().process();
    }
}

class Service2 {

    public void process() {
        User user = UserContextHolder.holder.get();
        ThreadSafeFormatter.dateFormatThreadLocal.get();
        System.out.println(Thread.currentThread().getName()+"中的Service2拿到用户名：" + user.name);
        new Service3().process();
    }
}

class Service3 {

    public void process() {
        User user = UserContextHolder.holder.get();
        System.out.println(Thread.currentThread().getName()+"中的Service3拿到用户名：" + user.name);
        UserContextHolder.holder.remove();
    }
}

class UserContextHolder {

    public static ThreadLocal<User> holder = new ThreadLocal<>();


}

class User {

    String name;

    public User(String name) {
        this.name = name;
    }
}